package com.hb.config.shiro.filter;

import cn.hutool.core.util.StrUtil;
import com.hb.commons.MsgEnum;
import com.hb.commons.ResponseDto;
import com.hb.config.shiro.JwtToken;
import com.hb.util.ContextUtil;
import com.hb.util.JwtUtils;
import com.hb.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description: 鉴权登录拦截器
 * @Author: Scott
 * @Date: 2018/10/7
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    private boolean allowOrigin = true;

    public JwtFilter() {
    }

    public JwtFilter(boolean allowOrigin) {
        this.allowOrigin = allowOrigin;
    }

    /**
     * 执行登录认证
     *
     * @param request
     * @param response
     * @param mappedValue
     *
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            return executeLogin(request, response);
        } catch (Exception e) {
            log.error("Token失效，请重新登录", e);
            // throw new AuthenticationException("Token失效，请重新登录", e);
        }
        ResponseDto resp = ResultUtil.msg(MsgEnum.LOGIN_ERROR);
        out(response, resp);
        return false;
    }

    /**
     *
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(JwtUtils.X_ACCESS_TOKEN);

        if (StrUtil.isNotEmpty(token) && JwtUtils.checkToken(token)) {
            JwtToken jwtToken = new JwtToken(token);

            // 提交给realm进行登入，如果错误他会抛出异常并被捕获
            getSubject(request, response).login(jwtToken);

            // 如果没有抛出异常则代表登入成功，返回true
            return true;
        }
        ResponseDto resp = ResultUtil.msg(MsgEnum.LOGIN_EXPIRE);
        out(response, resp);
        return false;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

//        String apiPath = httpServletRequest.getRequestURI(); // 请求的接口
//        log.info(apiPath);

        if (allowOrigin) {
            ContextUtil.preHandle(httpServletResponse, null);
        }
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 返回响应对象
     *
     * @param response
     * @param returnMap 响应消息对象
     */
    private void out(ServletResponse response, Object returnMap) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.print(returnMap);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
